import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
//引入获取用户菜单的方法
import { getMenuList } from "@/api" 
//引入动态路由
import DynamicRoutes from "@/router/DynamicRoutes"
//引入路由 
import router from "@/router"
//引入recursionRoutes递归函数处理用户路由
import recursionRoutes from "../utils/recurisionRoutes.js"
//引入allRoutes路由
import allRoutes from '../router/allRoutes.js'


let userInfo = JSON.parse(localStorage.getItem("user-userInfo")) || {};
let permissionButtons = JSON.parse(localStorage.getItem("user-permission")) || {};
export default new Vuex.Store({

  //刷新会重置
  state: {
    sideMenu:[],
    userInfo,
    permissionButtons,
    crumb:[]
  },
  mutations: {
    SET_SIDEMENU(state, payload){   //设置用户菜单
      state.sideMenu = payload 
      //找到"/"路径的路由，因为所有的路由页面都是他的子路由
      let target = DynamicRoutes.find(item => item.path === "/")
      target.children = [...state.sideMenu] // ...扩展运算符，将数组展开
      //addRoutes  动态添加更多的路由规则。参数必须是一个符合 routes 选项要求的数组
      router.addRoutes(DynamicRoutes)
   
    },
    //退出时清空sideMenu
    CLEAR_SIDEMENU(state){
      state.sideMenu = []
    },
    SET_USERINFO(state,payload){
      state.userInfo = payload
    },
    SET_PERMISSION_BUTTONS(state, payload){
      state.permissionButtons = payload
    },
    //设置面包屑的值
    SET_CRUMB(state, payload){
      state.crumb = payload
    }
  },
  actions: {
    //这里使用 async await是因为为了异步获取数据，要先等获取数据结束后再执行下面的同步结果，这样在main.js里面就不会没有数据直接直接next()
    async FETCH_MENULIST( {commit}){//获取用户菜单
      //发起异步请求，获取用户菜单
      let res = await getMenuList()
        
          if(res&&res.data){  //得到结果了
            // console.log(res.data);
            //递归获取用户路由
            let userMenu = recursionRoutes(allRoutes, res.data.menuList )
            commit("SET_SIDEMENU", userMenu)
          }
        
        }
      
    
  },

  modules: {
  }
})
